package com.baizhi.service.impl;
import com.baizhi.entity.*;
import com.baizhi.mapper.*;
import com.baizhi.service.CmfzChiroService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
public class CmfzChiroServiceImpl implements CmfzChiroService {
    @Autowired
    private CmfzAdminDAO cmfzAdminDAO;
    @Autowired
    private CmfzAdminRoleMapper cmfzAdminRoleMapper;
    @Autowired
    private CmfzRoleMapper cmfzRoleMapper;
    @Autowired
    private CmfzRoleResourceMapper cmfzRoleResourceMapper;
    @Autowired
    private CmfzResourceMapper cmfzResourceMapper;
    /*
    * 根据用户名获取 该用户的所有角色名
    * */
    @Override
    public Set<String> selectRoleNameByUsername(String username) {
        /*根据用户名获取管理员id*/
        CmfzAdmin admin = cmfzAdminDAO.selectOne(new QueryWrapper<CmfzAdmin>().eq("username", username));
        /*根据管理员id获取其 所有的角色id*/
        List<CmfzAdminRole> adminRoles = cmfzAdminRoleMapper.selectList(new QueryWrapper<CmfzAdminRole>().eq("admin_id", admin.getId()));
        Set<String> set = new HashSet<>();
        for (CmfzAdminRole adminRole : adminRoles) {
            /*将角色名称封装到set里面 返回*/
            set.add(cmfzRoleMapper.selectById(adminRole.getRoleId()).getRoleName());
        }
        return set;
    }

    @Override
    public Set<String> selectPermissionByUsername(String username) {
        /*根据用户名查询  该用户的所有角色名*/
        Set<String> set = selectRoleNameByUsername(username);
        Set<String> hashSet = new HashSet<>();
        for (String roleName : set) {
            List<CmfzRoleResource> roleResources = cmfzRoleResourceMapper.selectList(new QueryWrapper<CmfzRoleResource>().eq("role_name", roleName));
            for (CmfzRoleResource roleResource : roleResources) {
//                根据权限Id 查询权限表得到权限字符串  where resource_type=function
                CmfzResource cmfzResource = cmfzResourceMapper.selectOne(new QueryWrapper<CmfzResource>().eq("resource_id",roleResource.getResourceId()).eq("resource_type","function"));
                if (cmfzResource != null) {
                    hashSet.add(cmfzResource.getResourcePermission());
                }
            }
        }
        return hashSet;
    }
}
